package com.fingard.dsp.bank.directbank.qlb02;

import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;

/**
 * @author Parker on 2019-10-10.
 * @version 1.0
 */
public class QLB02BatPayRec extends QLB02Base implements IBatPayRec {

    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        // 返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
        try {
            String fileName = p_req9188.reqBatchNO + ".req";
            String filePath = getTempFileDirectory() + File.separator + "uploads" + File.separator + fileName;
            StringBuilder payFileContext = writerPayFileContext(p_req9188);
            FileHelper.writeFile(filePath, payFileContext.toString(),getCharset());
            WriteBankLogLn(p_req9188.reqBatchNO + "批号代收文件处理完毕,一共" + p_req9188.getTotalNum() + "条明细.");
            WriteBankLogLn("开始上传文件至FTP...");
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            String ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" + fileName;
            int result = FtpUtil.ftpUploading(ftpSet, filePath, ftpFilePath);
            if (result == 0 || result == 1) {
                WriteBankLogLn("上传批量付款文件成功...");
            } else {
                WriteBankLogLn("上传批量付款文件失败...");
                retAts.respCode = "-999";
                retAts.respInfo = "上传批量付款文件失败...";
                return retAts;
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
            xmlWriter.writeStartElement("stream");
            if ("918802".equals(p_req9188.reqHeader.commandCode)) {
                xmlWriter.writeElementString("action", "DLAGEPUB");//对公
            } else {
                xmlWriter.writeElementString("action", "DLAGENTF");//对私
            }
            xmlWriter.writeElementString("userName", "");
            xmlWriter.writeElementString("clientID", p_req9188.reqBatchNO);
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/stream/retcode");
                    String respondInfo = tmpBkReader.getFirstText("/stream/retmsg");
                    if("000000".equals(tmpRetCode)){
                        retAts.respCode = "0";
                        retAts.respInfo = "报文提交成功";
                        retAts.reqSeqID = p_req9188.reqBatchNO;
                        retAts.payInfoCode = tmpBkReader.getFirstText("/stream/status");
                        retAts.transState = retAts.payInfoCode;
                    }else{
                        retAts.respCode = "-999";
                        retAts.respInfo = respondInfo;
                    }
                } else {
                    retAts.respCode = "-999";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (bankResult[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = bankResult[1];
                retAts.reqSeqID = p_req9188.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = bankResult[0];
            } else {
                retAts.respCode = "-999";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-999";
            retAts.respInfo = e.toString();
            WriteBankLogLn("批量代发异常：" + e);
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-999") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req9188.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }


    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        // 返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
            xmlWriter.writeStartElement("stream");
            if ("918802".equals(p_req9198.reqHeader.commandCode)) {
                xmlWriter.writeElementString("action", "DLAGEPDT");//对公
            } else {
                xmlWriter.writeElementString("action", "DLAGEDET");//对私
            }
            xmlWriter.writeElementString("userName", "");
            xmlWriter.writeElementString("clientID", p_req9198.reqBatchNO);
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String status = tmpBkReader.getFirstText("/stream/status");
                    if ("1".equals(status)) {//下载文件
                        FtpSet ftpSet = bankFront.getFtpSet("bat");
                        String downFilePath = StringHelper.trimEndFileSp(ftpSet.downDir) + "/" + p_req9198.reqBatchNO + ".resp";
                        String localSavePath = getTempFileDirectory() + File.separator + "downloads" + File.separator + p_req9198.reqBatchNO + ".resp";
                        FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                        ftpPtClient.connect();
                        FtpReceiver ftpReceiver = ftpPtClient.downloadFile(downFilePath, localSavePath);
                        if (ftpReceiver.isCompleted) {
                            WriteBankLogLn("成功下载批量支付结果文件:" + p_req9198.reqBatchNO + ".resp" + "至" + localSavePath);
                        } else {
                            WriteBankLogLn(p_req9198.reqBatchNO + ".resp" + "批量支付结果文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                            retAts.respCode = "-1";
                            retAts.respInfo = p_req9198.reqBatchNO + ".resp" + "批量支付结果文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState;
                            retAts.writeAfterDetail();
                            return retAts;
                        }
                        if (FileHelper.existFile(localSavePath)) {
                            String[] fileContent = FileHelper.readFileText(localSavePath, getCharset()).split("\n");
                            String[] heads = fileContent[0].split(",");
                            retAts.reqSeqID = heads[0];//客户流水号
                            retAts.transState = heads[7];//交易状态
                            retAts.respInfo = heads[8];//交易状态信息
                            retAts.payInfoCode = heads[7];//交易状态
                            retAts.respCode = "0";

                            for (int i = 1; i < fileContent.length; i++) {
                                if (fileContent[i] != null) {
                                    RetAtsBatPayRecDetail detail = new RetAtsBatPayRecDetail();
                                    String[] bodys = fileContent[i].split(",");
                                    detail.payAct = bodys[0];//付款账号
                                    detail.payName = bodys[1];//付款账户名称
                                    detail.payAmount = bodys[2];//金额
                                    detail.postScript = bodys[4];
                                    if("00000".equals(bodys[7])){
                                        detail.result = status + "+" + bodys[7];//交易状态
                                    }else{
                                        detail.result = status + "+FAIL";//交易状态
                                    }
                                    detail.memo = bodys[8];//交易状态信息
                                    retAts.writeRetDetail(detail);
                                }
                            }
                        } else {
                            retAts.respCode = "-999";
                            retAts.respInfo = "查询成功，未获取到文件";
                        }
                    } else if ("2".equals(status) || "3".equals(status) || "4".equals(status) || "0".equals(status)) {
                        retAts.transState = status;
                        retAts.respCode = "0";
                        retAts.respInfo = "对私代收交易状态查询，银行处理状态：" + status;
                        retAts.reqSeqID = p_req9198.reqHeader.reqSeqID;
                        retAts.payInfoCode = status;
                    } else {
                        retAts.respCode = "-999";
                        retAts.respInfo = "银行返回状态异常：" + status;
                    }
                } else {
                    retAts.respCode = "-999";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (bankResult[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = bankResult[1];
                retAts.reqSeqID = p_req9198.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = bankResult[0];
            } else {
                retAts.respCode = "-999";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-999";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-999".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req9198.reqBatchNO;
        }
        if ("-999".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
